<?php

namespace app\user\controller;

use app\common\model\Users;
use think\Controller;
use think\Request;

class Account extends Controller
{

    // 登录页面
    public function login(Request $request)
    {
        if ( $request->isPost() ){
            $post = trimAll($request->post());

            if ( !$user = Users::where(['username'=>$post['username']])->find() ){
                createLog('没有此用户：' . $post['username']);
                error('没有此用户');
            }

            if ( $user['password'] !== sha1_password($post['password']) ){
                createLog('密码错误：' . $post['username'] . ' / ' . $post['password']);
                error('密码错误');
            }

            if ( ($user['admin'] != 2) && ($user['admin'] != 3) ){
                error('没有登录权限');
            }

            if ( $user['status'] != 1 ) {
                error('账号还没通过审核，请联系管理员！');
            }

            unset($user['password']);
            session('user', $user);

            createLog('登录成功');
            success('登录成功');
        }
        return view();
    }


    public function reg(Request $request)
    {
        if ( $request->isPost() ) {
            $post = trimAll($request->post());

            if ( strlen($post['username']) < 3 ) {
                error('用户名不能小于3位');
            }

            if ( strlen($post['password']) < 6 ) {
                error('密码不能小于6位');
            }

            if ( $post['password'] !== $post['repassword'] ) {
                error('两次输入的密码必须相同');
            }

            if ( Users::where(['username'=>$post['username']])->find() ) {
                error('用户已存在');
            }

			// 新用户试用期时长
	        $newuserendtime = (int)fission('newuserendtime');
			if ( $newuserendtime ) $newuserendtime = 3;

            $data = [
                'username' => $post['username'],
                'password' => sha1_password($post['password']),
                'admin'    => 2,
                'status'   => 2,
	            'create_time'=> time(),
	            'end_time'  => time() + 60*60*24*$newuserendtime  // 新用户试用期时长
            ];

            if ( Users::create($data) ) {
                createLog($post['username'] . ' 注册成功');
                success('注册成功');
            } else {
                error('注册失败');
            }

        }
        return view();
    }



	// 安全退出
	// /user/account/logout
	public function logout()
	{
		session('admin', null);
		cookie('authcode', null);
		session(null);
		cookie(null);
		success('已安全退出');
	}




}
